
package com.warpcode.gpsloggerlite;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;



public class MainPage extends Activity implements OnCheckedChangeListener,LocationListener
{                
	private final static String MANUAL_RADIO = "Manual Plot";
    private final static String INTERVAL_RADIO = "Interval Plot";
    private final static String MANUAL_BUTTON = "Get Current Location";
    private final static String INTERVAL_BUTTON = "Plot Locations";
    private final static String STOP_BUTTON = "Stop Plotting";
        
    public static final int SHOW_LOCATIONS_REQUEST_CODE = 1;
        
    private LocationManager locate;
    private NotificationManager mNotificationManager;
    private LocationDatabase db;
    private Button b;
    private RadioGroup mode;
    private Button d ;
        
    private int points = 0;
            
    private CountDown count = null;
    private int interval;
    private Time t;
    
    private TextView inst_lati;
    private TextView inst_longi;
    private TextView inst_alti;
    private TextView inst_speed;
    private TextView inst_accu;
        
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
                
        locate = (LocationManager) getSystemService(LOCATION_SERVICE);
        
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);	
                
        db = new LocationDatabase(this);
                
        d = (Button) findViewById(R.id.sDB);
                
        t = new Time();
                
        b = (Button) findViewById(R.id.pTrigger);
        
        inst_lati = (TextView) findViewById(R.id.lat_inst);
        inst_longi = (TextView) findViewById(R.id.long_inst);
        inst_alti = (TextView) findViewById(R.id.alt_inst);
        inst_speed = (TextView) findViewById(R.id.speed_inst);
        inst_accu = (TextView) findViewById(R.id.accu_inst);
                
        mode = (RadioGroup) findViewById(R.id.mode);
        mode.setOnCheckedChangeListener(this);
                                 
        if(locate.isProviderEnabled(LocationManager.GPS_PROVIDER))
        {
        	Toast.makeText(getApplicationContext(),"GPS is enabled on your device",Toast.LENGTH_SHORT).show();
        }
                
        else
        {
        	showGPSalert();
        }
    }
        
    private void createNotification()
    {
    	NotificationCompat.Builder mBuilder =
    			new NotificationCompat.Builder(this)
        	 	.setSmallIcon(R.drawable.ic_launcher)
        	    .setContentTitle("GPS Logger is running")
        	    .setContentText("GPS Logger has plotted " + points + " locations")
        	    .setOngoing(true)
        	    .setProgress(100, 50, true);
        	        
    	mNotificationManager.notify(0,mBuilder.build());	
    }
    
    private void removeNotification()
    {
        mNotificationManager.cancelAll();
    }
        
    public void displayIntervalDialog()
    {
    	LayoutInflater inflater = this.getLayoutInflater();
                
        final View view = inflater.inflate(R.layout.interval_dialog,null);
                
        final LocationListener ll = this;
                
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                 
        alertDialogBuilder.setView(view);
        alertDialogBuilder.setMessage("Choose an Interval for your plot in ( MM : SS )")
        	.setCancelable(false)
            .setNegativeButton("Set Interval",
            new DialogInterface.OnClickListener()
            {    
            	public void onClick(DialogInterface dialog, int id)
            	{   
            		EditText min = (EditText) view.findViewById(R.id.minsvalue);
            		EditText sec = (EditText) view.findViewById(R.id.secsvalue);
            		
            		int minInterval;
            		int secInterval;
            
            		if(!min.getText().toString().equals(""))
            		{   
            			minInterval = Integer.parseInt(min.getText().toString());
            		}
            		else
            			minInterval = 0;
            
            		if(!sec.getText().toString().equals(""))
            		{
            			secInterval = Integer.parseInt(sec.getText().toString());
            		}
            		else
            			secInterval = 0;    
            		try 
            		{
            			interval = (minInterval*60 + secInterval)*1000;
             
            			if(interval == 0)
            				throw new Exception();
            			
            			interval -= 1000;
             
            			String toast = "";
             
            			if(minInterval != 0)
            				toast += min.getText().toString()+" min ";
             
            			if(secInterval != 0)
            				toast += sec.getText().toString()+" sec ";
          
            			Toast.makeText(getApplicationContext(),toast, Toast.LENGTH_LONG).show(); 

            			d.setEnabled(false);
            			b.setText(STOP_BUTTON);
            			createNotification();
            			locate.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,ll);
            		}
            
            		catch(Exception e)
            		{
            			Toast.makeText(getApplicationContext(), "Please enter a valid interval", Toast.LENGTH_LONG).show();
            		}
            	}
            	});
            
        alertDialogBuilder.setPositiveButton("Cancel",
        		new DialogInterface.OnClickListener()
        		{
            		public void onClick(DialogInterface dialog, int id)
            		{
            			dialog.cancel();
            		}
        		});
        alertDialogBuilder.create().show();                 
    }
        
       
        
    public void onDestroy()
    {
    	super.onDestroy();
        RadioButton sel = (RadioButton) findViewById(mode.getCheckedRadioButtonId());
        if(b.getText().equals(STOP_BUTTON))
        {       
        	if(sel.getText().equals(MANUAL_RADIO))
        	{
        		b.setText(MANUAL_BUTTON);     
        	}
         
        	else if(sel.getText().equals(INTERVAL_RADIO))
        	{
        		b.setText(INTERVAL_BUTTON); 
                
                stopCountDown();
            }
        	locate.removeUpdates(this);
        }
        removeNotification();
    }
        
    @Override
    public void onCheckedChanged(RadioGroup mode, int arg1) 
    {
    	RadioButton sel = (RadioButton) findViewById(mode.getCheckedRadioButtonId());
        if (sel.getText().equals(MANUAL_RADIO))
        {                
        	b.setText(MANUAL_BUTTON);
            stopCountDown();
        }
                
        else if (sel.getText().equals(INTERVAL_RADIO))
        {             
        	b.setText(INTERVAL_BUTTON);            
        }
        d.setEnabled(true);
        locate.removeUpdates(this);        
   }
        
   private void showGPSalert()
   {
	   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
       alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
       		.setCancelable(false)
            .setNegativeButton("Enable GPS",
            new DialogInterface.OnClickListener()
            {
            	public void onClick(DialogInterface dialog, int id)
            	{
            		Intent callGPSSetting = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            		startActivity(callGPSSetting);
                }
            });
       
       alertDialogBuilder.setPositiveButton("Cancel",
    		new DialogInterface.OnClickListener()
       		{
            	public void onClick(DialogInterface dialog, int id)
               	{
            		dialog.cancel();
            		if(b.getText().equals(STOP_BUTTON))
            		{
            			gTrigger(null);
            		}
               	}
            });
       alertDialogBuilder.create().show();         
   }
        
   public void showLocations(View view)
   {
	   Intent i = new Intent(this,ShowLocationsActivity.class);
       startActivityForResult(i,SHOW_LOCATIONS_REQUEST_CODE);         
   }
        
   public void gTrigger(View view)
   {                
	   if (b.getText().equals(MANUAL_BUTTON))
       {         
		   b.setText(STOP_BUTTON);
                
           d.setEnabled(false);
           locate.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
           createNotification();
       	}
                
        else if(b.getText().equals(INTERVAL_BUTTON))    
        {                
        	displayIntervalDialog();
        }
                
        else if(b.getText().equals(STOP_BUTTON))
        {
        	d.setEnabled(true);
        	RadioGroup mode = (RadioGroup) findViewById(R.id.mode);
        	RadioButton sel = (RadioButton) findViewById(mode.getCheckedRadioButtonId());
        	if (sel.getText().equals(MANUAL_RADIO))
        	{
        		b.setText(MANUAL_BUTTON);
            }
                        
            else if (sel.getText().equals(INTERVAL_RADIO))
            {
            	b.setText(INTERVAL_BUTTON);
                                
                stopCountDown();                                
            }
            removeNotification();
            points = 0;
            locate.removeUpdates(this);     
        }       
   }
   
   private void stopCountDown()
   {
	   if(count != null)
       {       
		   if(count.isAlive())
		   {       
			   count.interrupt();
               count = null;
           }
       }
   }
        
   @Override
   public void onLocationChanged(Location loc) 
   {            
	   if(loc!=null)
	   {
		   instantPlot(loc);
                        
		   RadioButton sel = (RadioButton) findViewById(mode.getCheckedRadioButtonId()); 
                  
		                     
           if(sel.getText().equals(MANUAL_RADIO))
           {
        	   Time t = new Time();
               t.setToNow();
               db.addLocationAtTime(loc, t);
               Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();        
               locate.removeUpdates(this);
                      
               b.setText(MANUAL_BUTTON);
               d.setEnabled(true);

           }
                  
           else if(sel.getText().equals(INTERVAL_RADIO))
           {
        	   if(count == null)
        	   {
        		   t.setToNow();
                   db.addLocationAtTime(loc, t);
                   Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
                   count =  new CountDown(interval);
                   count.start();
                   points++;
        		   
        		   createNotification();

        	   }
                                  
        	   else if(count.getState().toString().equals("TERMINATED"))
        	   {
        		   t.setToNow();
        		   db.addLocationAtTime(loc, t);
        		   Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
        		   count =  new CountDown(interval);
        		   count.start();  
        		   points++;
        		   
        		   createNotification();

        	   }             
           }
	   }
   }
             
   public void instantPlot(Location loc)
   {             
	   inst_lati.setText(String.valueOf(loc.getLatitude()));
       inst_longi.setText(String.valueOf(loc.getLongitude()));
       inst_alti.setText(String.valueOf(loc.getAltitude()));
       inst_speed.setText(String.valueOf(loc.getSpeed()));
       inst_accu.setText(String.valueOf(loc.getAccuracy()));         
   }

   @Override
   public void onProviderDisabled(String provider) 
   {
	   showGPSalert();
   }

   @Override
   public void onProviderEnabled(String provider) 
   {
	   Toast.makeText(getApplicationContext(),"GPS is enabled on your device",Toast.LENGTH_SHORT).show();
   }

   @Override
   public void onStatusChanged(String provider, int status, Bundle extras) 
   {
	   if(status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE)
	   {   
		   Toast.makeText(getApplicationContext(),"Not able to get GPS fix",Toast.LENGTH_SHORT).show();
	   }
   }
        
   protected void onActivityResult(int requestCode,int responseCode,Intent intent)
   {
   }
}
